<?php

/**
 * @Author: CraspHB彬
 * @Date:   2018-03-28 15:56:57
 * @Email:   646054215@qq.com
 * @Last Modified time: 2018-03-29 17:15:23
 */
namespace app\admin\controller;
use think\Controller;
use think\Db;
use think\Request;
use app\admin\model\User as UserModel;

class User extends Base{
	public function index(){
		$where = [];
		$username = input('username')?input('username'):'';
		if(Request::instance()->isPost()){
			$where['username'] = ['like','%'.$username.'%'];
		}
        $user = Db::name('user')->where($where)->select();
        $this->assign('user',$user);
        $this->assign('username',$username);
		return $this->fetch();
	}
	/**
	 * 添加用户
	 */
	public function user_add(){
		return $this->fetch();
	}
	public function user_runadd(){
		if(Request::instance()->isAjax()){
	        $data = input('post.');
			if(request()->file('avatar')){
        		$avatar = upload_img(request()->file('pic'),'avatar');
	        	if(!$avatar['success']){
	        		$this->error($avatar['msg'],url('admin/User/index'));
	        	}
	        	$data['pic'] = $avatar['filename'];
        	}	        
	        $user = new UserModel();
	        if($user->user_add($data)){
	        	$this->success('用户添加成功',url('admin/User/index'));
	        }else{
	        	$this->error($user->getError(),url('admin/User/index'),$user->getData());
	        }
	    }else{
	   	  $this->error('提交方式不正确',url('admin/User/index'));
	   }
	}	
	/**
	 * 修改用户
	 * @return [type] [description]
	 */
	public function user_edit(){
		$id = input('id');
		$user = Db::name('user')->find($id);
		$this->assign('user',$user);
		return $this->fetch();
	}
	
	public function user_runedit(){
		if(Request::instance()->isAjax()){
	        $data = $_POST;
	        if(request()->file('pic')){
        		$avatar = upload_img(request()->file('pic'),'avatar');
	        	if(!$avatar['success']){
	        		$this->error($avatar['msg'],url('admin/User/index'));
	        	}
	        	$data['pic'] = $avatar['filename'];
        	}else{
        		unset($data['pic']);
        	}	     
	        $user = new UserModel();
	        if($user->user_edit($data)){
	        	$this->success('用户修改成功',url('admin/User/index'));
	        }else{
	        	$this->error($user->getError(),url('admin/User/index'));
	        }
	    }else{
	   	  $this->error('提交方式不正确',url('admin/User/index'));
	   }
	}
	/**
	 * 删除用户
	 * @return [type] [description]
	 */
	public function user_del(){
		if(Request::instance()->isAjax()){
	        $id = input('id');
	        if(Db::name('user')->delete($id)){
	        	$this->success('用户删除成功',url('admin/User/index'));
	        }else{
	        	$this->error('用户删除失败',url('admin/User/index'));
	        }
	    }else{
	   	  $this->error('提交方式不正确',url('admin/User/index'));
	   }
	}
	/**
	 * 修改状态
	 * @return [type] [description]
	 */
	public function user_status(){
        $id = input('get.id');
        $user = new UserModel();
        $res = $user->user_status($id);
        return $res;
	}	
}